package org.abc.fund.config.exception;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;

/**
 * 统一的安全执行切面：为指定包和类自动增加异常捕获与中文日志。
 * 这样可以避免接口直接抛出堆栈，保证返回更加友好。
 */
@Aspect
@Component
@Slf4j
public class SafeExecutionAspect {

    @Pointcut("within(org.abc.fund.controller.dataSource..*) " +
            "|| within(org.abc.fund.controller.dataUpdate..*) " +
            "|| within(org.abc.fund.service.dataSource..*) " +
            "|| within(org.abc.fund.service.dataSourceCollection..*) " +
            "|| within(org.abc.fund.service.funds.FundAutoTaggingService) " +
            "|| within(org.abc.fund.service.funds.TagClusterService) " +
            "|| within(org.abc.fund.service.funds.TagClusterWarmupScheduler)")
    private void monitoredComponents() {
        // Pointcut definition
    }

    @Around("monitoredComponents()")
    public Object wrapExecution(ProceedingJoinPoint joinPoint) throws Throwable {
        String actionName = resolveActionName(joinPoint);
        try {
            return joinPoint.proceed();
        } catch (ResponseStatusException ex) {
            log.warn("执行 {} 失败：{}", actionName, ex.getReason());
            throw ex;
        } catch (IllegalArgumentException | IllegalStateException ex) {
            log.warn("执行 {} 时检测到非法参数：{}", actionName, ex.getMessage());
            throw new ResponseStatusException(
                    HttpStatus.BAD_REQUEST,
                    buildFriendlyMessage("请求参数不合法", ex.getMessage()),
                    ex
            );
        } catch (Exception ex) {
            log.error("执行 {} 时发生系统异常", actionName, ex);
            throw new ResponseStatusException(
                    HttpStatus.INTERNAL_SERVER_ERROR,
                    "系统处理请求时出现异常，请稍后重试",
                    ex
            );
        }
    }

    private String resolveActionName(ProceedingJoinPoint joinPoint) {
        if (joinPoint.getSignature() instanceof MethodSignature methodSignature) {
            return methodSignature.getDeclaringType().getSimpleName() + "#" + methodSignature.getName();
        }
        return joinPoint.getSignature().toShortString();
    }

    private String buildFriendlyMessage(String prefix, String detail) {
        if (detail == null || detail.isBlank()) {
            return prefix;
        }
        return prefix + "：" + detail;
    }
}

